package com.zqh.wechatpay.controller;

import com.github.wxpay.sdk.WXPayUtil;
import com.zqh.myfmmall.clients.OrderUDClient;
import com.zqh.myfmmall.constants.OrderStatus;
import com.zqh.myfmmall.result.Result;
import com.zqh.myfmmall.result.ResultType;
import com.zqh.myfmmall.rowbeans.entity.Orders;
import com.zqh.wechatpay.service.WechatPayService;
import com.zqh.wechatpay.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description :
 * @Author :kono淇杭哒、
 * @Create 2022-02-28 22:43
 */
@Slf4j
@RequestMapping("wechatPay")
@RestController
public class WechatPayController{
    @Resource
    private WechatPayService wechatPayService;
    @Autowired
    private OrderUDClient orderUDClient;

    @PostMapping("pay")
    public Result pay(@RequestBody Map<String,String> orderInfoMap){
        String payUrl = null;
        try {
            payUrl = wechatPayService.wxPay(orderInfoMap);
            return Result.success(payUrl);
        } catch (Exception e) {
            log.warn("微信支付请求出错：" + e);
            return Result.internalServerError();
        }
    }

    @PostMapping("checkPayed")
    public Result checkPayed(String orderId){
        try {
            boolean isPayed = wechatPayService.checkPayed(orderId);
            return Result.success(isPayed);
        } catch (Exception e) {
            log.warn("查看微信订单是否支付请求失败：" + e);
            return Result.internalServerError();
        }

    }

    /**
     * 回调接口:当用户支付成功之后，微信支付平台就会请求这个接口，将支付状态的数据传递过来
     */
    @GetMapping("/success")
    public String paySuccess(HttpServletRequest request) throws Exception {
        // 1.接收微信支付平台传递的数据（使用request的输入流接收）
        ServletInputStream is = request.getInputStream();
        byte[] bs = new byte[1024];
        int len = -1;
        StringBuilder builder = new StringBuilder();
        while((len = is.read(bs))!=-1){
            builder.append(new String(bs,0,len));
        }
        String s = builder.toString();
        //使用帮助类将xml接口的字符串装换成map
        Map<String, String> map = WXPayUtil.xmlToMap(s);

        if(map!=null && "success".equalsIgnoreCase(map.get("result_code"))){
            //支付成功
            //2.修改订单状态为“待发货/已支付”
            String orderId = map.get("out_trade_no");
            Orders order = new Orders();
            order.setOrderId(orderId);
            order.setStatus(OrderStatus.NOT_DELIVERED);
            Result result = orderUDClient.update(order);
            if (result.getStatusCode().equals(ResultType.SUCCESS.getCode())){
                //3.通过websocket连接，向前端推送消息
                WebSocketServer.sendMsg(orderId,"success");

                //4.响应微信支付平台
                HashMap<String,String> resp = new HashMap<>();
                resp.put("return_code","success");
                resp.put("return_msg","OK");
                resp.put("appid",map.get("appid"));
                resp.put("result_code","success");
                return WXPayUtil.mapToXml(resp);
            }
            //修改订单操作失败，暂时不知道咋写，后期补充
        }
        return null;
    }
}
